import jofc2.model.*
import jofc2.model.elements.LineChart
import jofc2.model.axis.YAxis
import jofc2.model.axis.XAxis
import jofc2.model.axis.Label
import jofc2.model.elements.AreaHollowChart
import jofc2.model.elements.PieChart
import jofc2.model.axis.Label.Rotation
import jofc2.model.elements.BarChart
import jofc2.OFC
import jofc2.model.elements.FilledBarChart
import jofc2.model.elements.SketchBarChart
import jofc2.model.elements.HorizontalBarChart
import jofc2.model.elements.ScatterChart
import java.math.MathContext
import jofc2.model.elements.StackedBarChart
import jofc2.model.elements.StackedBarChart.StackValue
import jofc2.model.elements.Legend


class ScoreAnalyzeController {

    def index = {
        if (params.id) {
            [ classes : Classes.get(params.id) , term : Term.currentTerm()]
        }else{
            flash.message = "必须首先确定班级。"
        } 
    }
    def top = {
        def courses = params.course
        if (!courses in Object[]) {
            courses = [params.course]
        }
 
        def classes = Classes.get(params.classesId)

        // ==========================
        def scoreArray = []
        classes?.student?.each{ std->
            scoreArray.add([std ,
             Score.withCriteria {
                and{
                    eq('student', std)
                    eq('team', params.team.toInteger())
                    eq('grade', params.grade.toInteger())
                    eq('term', params.term)
                    eq('year', Calendar.instance.get(Calendar.YEAR))
                }
            }])
        }
        scoreArray.each{
            if (it[1]) {
                it.add(it[1].score.sum())
            }
        }

        // 成绩排序
        if (params.sort) {
            
            Collections.sort(scoreArray, [
                compare: {a,b-> 
                    if (a.size() == 1 || b.size() == 1) {
                        return 0
                    }
                    if (params?.sort == 'total') {
//                        log.info "${a[2]} / ${b[2]}"
                        return a[2] == b[2]? 0: Math.abs(a[2])>Math.abs(b[2])? -1: 1
                        
                    }
                    def atemp = a[1].find{
                        it.course == params.sort
                    }
                    def btemp = b[1].find{
                        it.course == params.sort
                    }
                    if (!atemp  || !btemp ) {
                        return 0
                    }
                    atemp.score.equals( btemp.score)? 0: Math.abs(atemp.score)>Math.abs(btemp.score)? -1: 1
                }
                ] as Comparator
            );
        
        }
 
        ['classes' : classes , "courses" : courses , 
        'term' : params.term ,'grade' : params.grade,'team' : params.team,
        'history': scoreArray] 
    }
// 显示班级考试分数柱状图的页面
    def classesTop = {
        def exam = Exam.get(params.id)
        [exam : exam ,  count : Score.countByExam(exam)]
    }
// 显示班级考试分数柱状图的页面 的json
    def classesTopChart = {
        log.info "ScoreAnalyzeController. classesTopChart in come!!"
        def exam = Exam.get(params.id)
        if (exam) {
            if (params.order) {
                params.sort = 'score'
            } 
            def scores = Score.findAllByExam(exam, params) 

            def chart = new Chart("${exam}").setYAxis(new YAxis().setRange(0, exam.maximum, 10)).setBackgroundColour("#ECF9FF");
 
            def xaxis = new XAxis().setTickHeight(10).set3D(3).setColour("#909090");
            //def line = new LineChart(LineChart.Style.HOLLOW);  
            def element = new BarChart(BarChart.Style.THREED).setColour("#5579FF").setTooltip("#x_label# #x# #label#<br>#val#");
            //element.setHaloSize(0).setWidth(2).setDotSize(4);
  
            scores.each { score -> 
                def bar
                if (score.score >= exam.best) {// 优秀
                    bar = new BarChart.Bar(score.score, "#3333FF") 
                }else if (score.score >= exam.pass){//及格
                    bar = new BarChart.Bar(score.score) 
                }else{// 不及格
                    bar = new BarChart.Bar(score.score, "#FF6666") 
                }
                bar.setTooltip("${score?.student?.toString()}<br>${score.score}")
                element.addBars(bar)
                xaxis.addLabels(new Label(score?.student?.toString()))  
            }
 
            chart.setXAxis(xaxis).addElements(element)
            //.setXLegend(new Text("tests", Text.TEXT_ALIGN_CENTER ) )
 
            //        println chart.toDebugString()
            return render(chart)
        }
        []
    }
/* ==================================================
//  某班级考试及格率 饼图
====================================================*/
    def passPie = {
        def exam = Exam.get(params.id)
        [exam : exam ,  count : Score.countByExam(exam)]
    }

   def passPieChart = {
        def exam = Exam.get(params.id) 
        
        def piechart = new PieChart().setAnimate(true).setStartAngle(35).setBorder(2).setAlpha(0.6f).setColours("#d01f3c", "#356aa0", "#C79810").setTooltip("#label#<br>#val# of #total#<br>#percent# of 100%")
        piechart.addSlice(Score.countByExamAndScoreBetween(exam, 0,exam.pass-1), "不及格")
        if (params.order) {  
            piechart.addSlice(Score.countByExamAndScoreBetween(exam, exam.pass,exam.maximum), "及格")
        }else{
            piechart.addSlice(Score.countByExamAndScoreBetween(exam, exam.pass,exam.best-1), "及格")
            piechart.addSlice(Score.countByExamAndScoreBetween(exam, ,exam.best,exam.maximum), "优秀")
        }
        Chart chart = new Chart("${exam}及格率")
        chart.getTitle().setStyle(Text.createStyle(14, '#000000', Text.TEXT_ALIGN_LEFT) )
        chart.addElements(piechart)
        render chart
    }

/* ==================================================
// 显示班级考试分数柱状图的页面
====================================================*/    
    def courseLine = {
        def student = Student.get(params.id) 
        [student : student ,  course : encode(params.course)]
    }
// 显示班级考试分数柱状图的页面 的json
    def courseLineChart = {
            params.course = decode(params.course) 
            log.info "ScoreAnalyzeController. courseLineChart  params.max.toInteger() =${params.max?.toInteger()}"
            def student = Student.get(params.id)
           
            
            def scores = Score.withCriteria{
                eq('student' , student)
                exam{
                    eq('course' , params.course)
                    order('startTime', 'asc')
                } 
                if (params.max) {
                    maxResults(params.max.toInteger())
                }
            } 
         
            def chart = new Chart("${student}${params.course}课近期的考试成绩分析").setYAxis(new YAxis().setRange(0, 120, 10)).setBackgroundColour("#ECF9FF");
 
            def xaxis = new XAxis().setTickHeight(10).set3D(3).setColour("#909090");
            def element = new LineChart(LineChart.Style.HOLLOW).setHaloSize(1).setWidth(3).setDotSize(4).setTooltip("${params.course}成绩：#val#分")  
//            def element = new BarChart(BarChart.Style.THREED).setColour("#5579FF");
           
//  
            scores.each { score -> 
                if (score.score >= score.exam.best) {// 优秀
                    element.addValues(score.score)
                }else if (score.score >= score.exam.pass){//及格
                    element.addValues(score.score)
                }else{// 不及格
                    element.addDots(new LineChart.Dot(score.score, "#FF6666" , 5,1))  
                } 
                xaxis.addLabels(new Label("${score?.exam?.title}\n${score?.exam?.startTime?.format('MM-dd')}"))  
            }
// 
            chart.setXAxis(xaxis).addElements(element)
 
            //        println chart.toDebugString()
            return render(chart) 
    }
//==================================================
// 显示班级考试分数柱状图的页面
//==================================================

    def courseAllLine = {
        def student = Student.get(params.id) 
        [student : student ]
    }
// 显示班级考试分数柱状图的页面 的json
    def courseAllLineChart = {
        def student = Student.get(params.id) 

        def c = new Chart("${student}近期各科的考试成绩分析").setYAxis(new YAxis().setRange(0, 120, 10))
        def l1 = new LineChart(LineChart.Style.DOT).setTooltip("语文成绩：#val#分").setColour() 
        def l2 = new LineChart(LineChart.Style.DOT).setTooltip("数学成绩：#val#分")  
        def l3 = new LineChart(LineChart.Style.DOT).setTooltip("英语成绩：#val#分")  

        l1.setHaloSize(1).setWidth(4).setDotSize(4).setColour("#52C13B")
        l2.setHaloSize(1).setWidth(4).setDotSize(4).setColour("#F5CB4B")
        l3.setHaloSize(1).setWidth(4).setDotSize(4).setColour("#4BC1F2")

        for (int i = 0; i < 20; i++ ) {
          l1.addValues(40+Math.round((Math.random()*80)));
          l2.addValues(40+Math.round((Math.random()*80)));
          l3.addValues(40+Math.round((Math.random()*80)));
        }

        c.addElements(l1, l2, l3);

        render c;
    }

    private encode(String key){
        return key.encodeAsURL().replace(/%/ , '=') 
    }
    private decode(String key){
         return  key.replace(/=/, '%').decodeURL()
    }

//==================================================
//==================================================

}
